/**
 * 音频生成工具
 * 用于生成应用的各种音效
 */

/**
 * 生成启动音效
 * 一个优雅的渐进式和弦音效
 */
export async function generateStartupSound(): Promise<AudioBuffer> {
  // 创建音频上下文
  const audioContext = new (window.AudioContext || (window as any).webkitAudioContext)();

  // 音效参数
  const sampleRate = audioContext.sampleRate;
  const duration = 1.5; // 1.5秒
  const length = sampleRate * duration;

  // 创建音频缓冲区
  const audioBuffer = audioContext.createBuffer(2, length, sampleRate);

  // 和弦频率 (C大调和弦：C-E-G)
  const frequencies = [
    261.63, // C4
    329.63, // E4
    392.0 // G4
  ];

  // 为每个声道生成音频数据
  for (let channel = 0; channel < audioBuffer.numberOfChannels; channel++) {
    const channelData = audioBuffer.getChannelData(channel);

    for (let i = 0; i < length; i++) {
      const time = i / sampleRate;
      let sample = 0;

      // 生成和弦
      frequencies.forEach((freq, index) => {
        // 每个音符有不同的延迟开始时间，创造渐进效果
        const startTime = index * 0.1;
        if (time >= startTime) {
          const adjustedTime = time - startTime;
          // 使用正弦波生成音调
          const tone = Math.sin(2 * Math.PI * freq * adjustedTime);
          // 添加包络，创造淡入淡出效果
          const envelope = Math.exp(-adjustedTime * 1.5) * Math.min(adjustedTime * 10, 1);
          sample += tone * envelope * 0.2; // 降低音量
        }
      });

      // 整体淡出效果
      const globalEnvelope = Math.max(0, 1 - time / duration);
      channelData[i] = sample * globalEnvelope;
    }
  }

  return audioBuffer;
}

/**
 * 播放音频缓冲区
 */
export async function playAudioBuffer(audioBuffer: AudioBuffer, volume: number = 0.5): Promise<void> {
  return new Promise((resolve) => {
    const audioContext = new (window.AudioContext || (window as any).webkitAudioContext)();

    // 创建音源
    const source = audioContext.createBufferSource();
    source.buffer = audioBuffer;

    // 创建音量控制
    const gainNode = audioContext.createGain();
    gainNode.gain.value = volume;

    // 连接音频节点
    source.connect(gainNode);
    gainNode.connect(audioContext.destination);

    // 播放完成时resolve
    source.onended = () => {
      resolve();
    };

    // 开始播放
    source.start(0);
  });
}

/**
 * 生成并播放启动音效
 */
export async function playStartupSound(volume: number = 0.3): Promise<void> {
  try {
    const audioBuffer = await generateStartupSound();
    await playAudioBuffer(audioBuffer, volume);
  } catch (error) {
    console.warn('播放启动音效失败:', error);
  }
}
